package local

import (
	"context"
	"errors"
	"fmt"
	"github.com/spf13/cast"
	"log"
	"xiuxian_help_tool/backend/model/res"
	"xiuxian_help_tool/backend/service/remote"
	"xiuxian_help_tool/backend/service/remote/model"
	"xiuxian_help_tool/backend/utils/sdk"
	xiuXianba "xiuxian_help_tool/backend/utils/sdk/xiuxianba"
)

type CardService struct {
}

var CardServiceApp = new(CardService)

func (c *CardService) EnableCardByStage(req model.BoxesStageEnableReq) model.BoxesStageEnableRes {
	totalEnable := int32(0)

	_, cardMap, boxes := ReadCardFileData(req.FileId)
	errMsgDesc := "全部开启成功"
	if len(req.BoxesStage) == 0 {
		return model.BoxesStageEnableRes{
			Num: totalEnable,
			Msg: "请选择盒子与阶段信息",
		}
	}
	for _, boxInfo := range req.BoxesStage {
		for _, stage := range boxInfo.List {
			stageInfo := extractStageInfo(boxes, boxInfo.BoxIndex, cast.ToInt64(stage))
			if stageInfo == nil {
				errMsgDesc += fmt.Sprintf("找不到卡片范围: %d-%d\n", stageInfo.StartNum, stageInfo.EndNum)
				log.Println(errMsgDesc)
				continue
			}
			num := EnableCard(cardMap, stageInfo.StartNum, stageInfo.EndNum, req.Enable, req.Enable, cast.ToInt64(req.ParentId))
			totalEnable += num
		}

	}
	return model.BoxesStageEnableRes{
		Num: totalEnable,
		Msg: errMsgDesc,
	}
}

// 提取指定卡片
func extractStageInfo(boxes []res.BoxInfo, boxIndex int, startNum int64) *res.StageInfo {
	// 提取指定index
	box := boxes[boxIndex-1]
	// 提取指定卡片
	for _, info := range box.List {
		if info.StartNum == startNum {
			// 提取指定卡片
			return &info
		}
	}
	return nil
}

func EnableCard(cardMap map[int64]res.CardInfo, accountStart, accountEnd int64, enable, paid bool, parentUid int64) int32 {
	startKey, endUqKey, ok := FindRangeUqKey(cardMap, accountStart, accountEnd)
	if !ok {
		log.Fatalln("找不到卡片范围")
		return 0
	}
	// startKey 查找出detail 包含batchId
	card, err := remote.FindCardByUqKey(startKey)
	if err != nil {
		log.Println(fmt.Sprintf("查找卡片失败: %d-%d", accountStart, accountEnd))
		return 0
	}
	reqBody := model.UsersInviteCardMultiEditReq{
		StartUqKey:         startKey,
		EndUqKey:           endUqKey,
		BatchId:            card.BatchId,
		Enable:             enable,
		Paid:               paid,
		UsageCount:         card.UsageCount,
		SpecialUsageCount:  card.SpecialUsageCount,
		Price:              card.Price,
		Cover:              card.Cover,
		ActivationDeadline: card.ActivationDeadline,
		ValidDays:          card.ValidDays,
		ParentUid:          card.ParentUid,
	}
	if parentUid > 0 {
		reqBody.ParentUid = cast.ToString(parentUid)
	}
	numResp, err := CardRangeEdit(reqBody)
	if err != nil {
		log.Fatalln("开启卡片失败")
		return 0
	}
	return int32(numResp.Num)
}

// FindRangeUqKey 找到两个卡片的 UqKey
func FindRangeUqKey(cards map[int64]res.CardInfo, account1, account2 int64) (int64, int64, bool) {
	var ok bool
	var ok2 bool
	var uqKey1 res.CardInfo
	var uqKey2 res.CardInfo
	uqKey1, ok = cards[account1]
	uqKey2, ok2 = cards[account2]
	if ok && ok2 {
		return uqKey1.UqKey, uqKey2.UqKey, true
	}
	return 0, 0, false
}

func CardRangeEdit(payloadObj model.UsersInviteCardMultiEditReq) (resp *model.NumResp, err error) {
	ctx := context.Background()
	var result *sdk.APIRes[*model.NumResp]
	err = xiuXianba.XiuXianCli.Post("/backend/api/v1/card/multiEdit").
		SetBody(payloadObj).
		Do(ctx).Into(&result)
	if err != nil {
		return
	}
	if result != nil && result.Code == 0 {
		return nil, errors.New("开启卡片失败")
	}
	return result.Data, nil
}
